#include "ticketexplorer.h"

#include "ticketquery.h"
#include "ticket.h"
#include "ticketchangeset.h"
#include "ticketitemmodel.h"

#include <QtCore/QUrl>

class TicketExplorerPrivate {
public:
    TicketExplorerPrivate(ITicketExplorerBackend *backend)
        : be(backend)
    {    }

    ~TicketExplorerPrivate()
    {
        delete be;
    }


    ITicketExplorerBackend *backend() const { return be; }

    QList<TicketField> *ticketFields;

    ITicketExplorerBackend *be;
};

TicketExplorer::TicketExplorer(ITicketExplorerBackend *backend)
    : QObject(0), d(new TicketExplorerPrivate(backend))
{
    d->backend()->updateFields();
    connect(d->backend(), SIGNAL(fieldsUpdated()), this, SIGNAL(fieldDefinitionsUpdated()));
    connect(d->backend(), SIGNAL(error(TicketError)), this, SIGNAL(error(TicketError)));
}

TicketExplorer::~TicketExplorer()
{
    delete d;
}

QString TicketExplorer::backendId() const
{
    return d->backend()->id();
}

BaseTicketItemModel * TicketExplorer::modelQuery(TicketQuery query) const
{
    BaseTicketItemModel *model = d->backend()->queryModel(query);
    return model;
}

Ticket *TicketExplorer::createTicket() const
{
    Ticket *t = d->backend()->createTicket();
    return t;
}

QList<TicketField> TicketExplorer::getAvailableFields() const
{
    return d->backend()->getAvailableFields();
}

void TicketExplorer::updateFieldDefinitions()
{
    d->backend()->updateFields();
}

void TicketExplorer::updateTicket(Ticket *ticket)
{
    d->backend()->storeTicket(ticket);
}

QAbstractItemDelegate * TicketExplorer::ticketListDelegate() const
{
    return d->backend()->listDelegate();
}

void TicketExplorer::listChangedTickets(const QDateTime &since) const
{
    d->backend()->loadChangedTickets(since);
    connect(d->backend(), SIGNAL(changedTickets(QList<int>)),
            this, SIGNAL(changedTickets(QList<int>)), Qt::UniqueConnection);
}

QUrl TicketExplorer::remoteUrl() const
{
    return d->backend()->url();
}

QString TicketExplorer::username() const
{
    return d->backend()->username();
}
